//
//  GenericRequestInterceptor.swift
//  AlamofireRetrier
//
//  Created by 李煜 on 2024/6/13.
//https://blog.csdn.net/gang544043963/article/details/119817922
let gatewayBaseUrl: String? = ""
let accessToken: String = ""

import UIKit
import Alamofire
// 新建一个自定义Interceptor, 遵从 RequestInterceptor 协议
class GenericRequestInterceptor: RequestInterceptor {
    func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
        var request = urlRequest
        //Just for gatway host
        guard let baseUrl = gatewayBaseUrl, !accessToken.isEmpty else {
            return completion(.success(request))
        }
        if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(baseUrl) {
            // set JWT token to request header
            request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
        }
        
        completion(.success(request))
    }
    
    func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
        guard let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 else {
            completion(.doNotRetry)
            return
        }
        
        // 确保只重试一次，否则就无限重试下去了
        guard request.retryCount == 0, let baseUrl = gatewayBaseUrl else { return completion(.doNotRetry) }
        
        // 如果是特定 URL 并且状态码是 401
        if let urlString = request.firstRequest?.url?.absoluteString, urlString.hasPrefix(baseUrl) {
            // 重新获取 token
            gatewayAuthService?.refreshJWT(createURLRequest: createURLRequestFunc, complete: {[weak self] accessToken in
                if !accessToken.isEmpty {
                    // 保存新的 token，重试的时候在 adapter 中使用
                    self?.accessToken = accessToken
                    // 重试
                    completion(.retry)
                } else {
                    completion(.doNotRetry)
                }
            })
        } else {
            completion(.doNotRetry)
        }
    }
}
